<?php


namespace App\Services;


use App\Exceptions\BusinessException;
use App\Models\Member;
use App\Models\MemberIntegralLog;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class IntegralService
{
    public function store(string $miniType, int $memberId, int $integral, string $type, string $content): int
    {
        $lock = Cache::lock(sprintf('[%d]member_change_integral_by_%s_%s', $memberId, $miniType, $type), 10);

        try {
            $lock->block(5);

            $log = MemberIntegralLog::create([
                'member_id' => $memberId,
                'change'    => $integral,
                'type'      => $type,
                'content'   => $content,
                'mini_type' => $miniType,
            ]);

            Member::query()->where('id', $memberId)->increment('integral', $integral);

            return $log->id;
        } catch (LockTimeoutException $e) {
            throw new BusinessException('操作频繁');
        } catch (\Exception $e) {
            log_exception('记录用户积分日志异常', $e);
            throw new BusinessException('记录用户积分操作失败');
        } finally {
            optional($lock)->release();
        }
    }
}
